package test.serverframe.armc.server.manager.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import test.serverframe.armc.server.manager.common.ResultDtoUtil;
import test.serverframe.armc.server.manager.dto.ResultDto;

import org.quartz.*;
import org.quartz.utils.Key;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by EalenXie on 2018/6/4 16:12
 */

@Api("任务控制")
@Validated
@RequestMapping("/jobControl")
@RestController
public class JobController {

    private static Logger logger = LoggerFactory.getLogger(JobController.class);
    @Autowired
    private SchedulerFactoryBean factory;
    
    public static ExecutorService pool = Executors.newFixedThreadPool(10);
    
    /**
     * @Descripttion 初始化启动所有的Job
     * @Author LSY
     * @Date 2018/10/15 13:34
     **/
    @PostMapping("/InitAll")
    @ApiOperation(notes = "初始化调度",value = "初始化调度",httpMethod = "POST")
    //@PostConstruct
    public void initialize() {
        try {
            //reStartAllTaskJobs();
            logger.info("INIT SUCCESS");
        } catch (Exception e) {
            logger.info("INIT EXCEPTION : " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * @Descripttion 重启单个任务调度
     * @Author LSY
     * @Date 2018/10/15 15:08
     * @Param [id 任务调度id]
     * @Return 成功失败信息
     **/
    /*@RequestMapping("/refresh/{id}")
    @ApiOperation(notes = "根据任务调度ID重启任务调度",value = "根据任务调度ID重启任务调度",httpMethod = "POST")
    public ResultDto<String> refresh(@PathVariable String id) {
    	ResultDto<String> result = null;
        try {
        	Scheduler scheduler = factory.getScheduler();
        	CountDownLatch counter = new CountDownLatch(1);
        	pool.execute(new ScheduleThread(id, scheduler, true, Constants.REFLECTION_CLASS_NAME, 
        			Constants.REFLECTION_METHOD_NAME, false, null, null));
        	counter.countDown();
        	scheduler.start();
        	result = ResultDtoUtil.success();
		} catch (Exception e) {
			result = ResultDtoUtil.error(500, "重启单个任务调度失败");
			logger.info("error:", e);
		}
        return result;
        
    }*/
    
    /**
     * @return 
     * @Descripttion 重启所有任务调度 
     * @Author LSY
     * @Date 2018/10/15 14:41
     * @Return
     **/
   /* @ApiOperation(notes = "重启所有Job",value = "重启所有Job",httpMethod = "POST")
    @RequestMapping("/refresh/all")
    private ResultDto<String> reStartAllTaskJobs() {
    	ResultDto<String> result = null;
    	try {
    		List<String> taskInvokeIdList = jobService.loadInvokeTaskIds();
    		Scheduler scheduler = factory.getScheduler();
    		CountDownLatch counter = new CountDownLatch(taskInvokeIdList.size());
    		for (String id : taskInvokeIdList) {
    			pool.execute(new ScheduleThread(id, scheduler, true, Constants.REFLECTION_CLASS_NAME, 
    					Constants.REFLECTION_METHOD_NAME, false, null, null));
    		}
    		counter.countDown();
    		scheduler.start();
    		result = ResultDtoUtil.success();
		} catch (Exception e) {
			result = ResultDtoUtil.error(500, "重启所有任务调度失败");
			logger.error("重启所有任务调度失败", e);
		}
        
        return result;
    }*/
    
    /*
     * 停止所有调度
     * @author yegui  
     * @date 2018年12月15日  
     * @param taskInvokeId
     * void
     */
    @RequestMapping("/shutdownOneInvoke/{taskInvokeId}")
    @ApiOperation(value = "重启所有Job",httpMethod = "POST")
    public ResultDto<String> shutdownOneInvoke(@ApiParam @PathVariable String taskInvokeId){
    	ResultDto<String> result = null;
    	Scheduler scheduler = factory.getScheduler();
    	try {
			scheduler.shutdown();
			result = ResultDtoUtil.success();
		} catch (SchedulerException e) {
			result = ResultDtoUtil.error(500, "停止所有调度异常");
			logger.error("停止调度失败", e);
		}
    	return result;
    }
    
    /*
     * 暂停一个调度
     * @author yegui  
     * @date 2018年12月17日  
     * @param taskInvokeId
     * @return ResultDto<String>
     */
    @RequestMapping("/pauseOneInvoke/{taskInvokeId}")
    @ApiOperation(value = "暂停一个调度",httpMethod = "POST")
    public ResultDto<String> pauseOneInvoke(@ApiParam @PathVariable String taskInvokeId) {
    	ResultDto<String> result = null;
    	Scheduler scheduler = factory.getScheduler();
    	try {
    		JobKey jobKey = JobKey.jobKey(taskInvokeId, Key.DEFAULT_GROUP);
			scheduler.pauseJob(jobKey);
			result = ResultDtoUtil.success();
		} catch (Exception e) {
			result = ResultDtoUtil.error(500, "暂停这个调度失败");
			logger.error("暂停调度错误，taskInvokeId: " + taskInvokeId, e);
		}
    	return result;
    }
    
    /*
     * 重启一个已暂停的调度
     * @author yegui  
     * @date 2018年12月17日  
     * @param taskInvokeId
     * @return ResultDto<String>
     */
    @RequestMapping("/resumOneInvoke/{taskInvokeId}")
    @ApiOperation(value = "重启一个已暂停的调度",httpMethod = "POST")
    public ResultDto<String> resumeOneInvoke(@ApiParam @PathVariable String taskInvokeId) {
    	ResultDto<String> result = null;
    	Scheduler scheduler = factory.getScheduler();
    	try {
    		JobKey jobKey = JobKey.jobKey(taskInvokeId, Key.DEFAULT_GROUP);
			scheduler.resumeJob(jobKey);
			result = ResultDtoUtil.success();
		} catch (Exception e) {
			result = ResultDtoUtil.error(500, "重启调度失败");
			logger.error("重启调度，taskInvokeId: " + taskInvokeId, e);
		}
    	return result;
    }
    
   /* @RequestMapping("/startOneInvoke/{taskInvokeId}")
    @ApiOperation(notes = "根据任务调度ID启动任务调度",value = "根据任务调度ID启动任务调度",httpMethod = "POST")
    public ResultDto<String> startOneInvoke(String taskInvokeId) {
    	ResultDto<String> result = null;
        try {
        	Scheduler scheduler = factory.getScheduler();
        	CountDownLatch counter = new CountDownLatch(1);
        	pool.execute(new ScheduleThread(taskInvokeId, scheduler, false, Constants.REFLECTION_CLASS_NAME, 
        			Constants.REFLECTION_METHOD_NAME, false, null, null));
        	counter.countDown();
        	scheduler.start();
        	result = ResultDtoUtil.success();
		} catch (Exception e) {
			result = ResultDtoUtil.error(500, "启动单个任务调度失败");
			logger.info("启动单个任务调度失败，taskInvokeId" + taskInvokeId, e);
		}
        return result;
        
    }*/
    
}


